import {
  login,
  logout,
  getInfo
} from '@/api/app'
import {
  getToken,
  setToken,
  removeToken,
  getUserId,
  setUserId
} from '@/utils/auth'
import router, {
  resetRouter
} from '@/router'

const state = {
  token: getToken(),
  userId: getUserId(),
  name: '',
  avatar: '',
  status: '',
  full_name: '',
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER_ID: (state, userId) => {
    state.userId = userId
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_STATUS: (state, status) => {
    state.status = status
  },
  SET_FULL_NAME: (state, value) => {
    state.full_name = value
  }
}

const actions = {
  login ({
    commit
  }, userInfo) {
    const {
      username,
      password,
      captcha,
      captchaKey
    } = userInfo
    return new Promise((resolve, reject) => {
      login({
        username: username.trim(),
        password,
        captcha,
        captcha_key: captchaKey
      }).then(response => {
        const {
          token,
          user
        } = response
        commit('SET_TOKEN', token)
        commit('SET_USER_ID', user.id)
        setUserId(user.id)
        setToken(token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  getInfo ({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      getInfo({
        id: state.userId
      }).then(response => {
        if (!response) {
          reject(new Error('확인하지 못했습니다. 다시 로그인하십시오.'))
        }

        const {
          // roles,
          name,
          avatar,
          status,
          id
        } = response

        const roles = [{
          name: response.is_instructor === 0 ? 'superadmin' : 'instructor'
        }]
        response.roles = roles

        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject(new Error('비어 있지 않은 배열이어야합니다!'))
        }

        commit('SET_ROLES', roles.map(e => e.name))
        commit('SET_STATUS', status)
        commit('SET_FULL_NAME', response.full_name)
        commit('SET_USER_ID', id)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png')
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout ({
    commit,
    state,
    dispatch
  }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_USER_ID', 0)
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, {
          root: true
        })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken ({
    commit
  }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_USER_ID', 0)
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles ({
    commit,
    dispatch
  }, role) {
    // eslint-disable-next-line no-async-promise-executor
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)

      const {
        roles
      } = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, {
        root: true
      })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, {
        root: true
      })

      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
